-module(check_distribution).

-compile(export_all).


run_test() ->
    DbNodes = test_lib:all_db_nodes(),
    
    Replies = [{gen_server:call({backend,Node}, {status}),Node} 
              || Node <- DbNodes],

    F = [{Node,Size} || {{_,[Size]},Node} <- Replies],

    {Std,Tot} = get_stddev(F),
    {Fmt,Params} = intervals(F),
    Apa = "Avg Distribution: ~w\nStandard dev: ~w\nTotal dev: ~w\n"++Fmt,
    {Apa,[get_avg(F),Std,Tot]++Params}.


intervals(Values) ->
   Avg = get_avg(Values),
   Sizes = [S || {_,S} <- Values],
   SortedSizes = lists:sort(Sizes),
   ScaleLength = lists:max(SortedSizes),
   IntervalLength = ScaleLength / 11,
   Intervals = [{[S || S <- SortedSizes, (S =< IntervalLength*X) and
                  (S > IntervalLength*(X-1)) ],(Avg =< IntervalLength*X) and (Avg > IntervalLength*(X-1))} || X <- lists:seq(1,11) ],
   Percents = lists:map(fun({X,_})-> (length(X) / length(Sizes)) * 100 end, Intervals),
   Apa = lists:foldl(fun({_,B}, Acc) ->
                         Acc ++ "| ~.2f" ++ case B of
                                               true  -> "* ";
                                               false -> " "
                                           end
                     end, "", Intervals),
   {"\nData distribution statistics:~n~n"++Apa++"|\n",Percents}.


get_avg(Time) ->
   Sum = lists:foldl(fun({_,T},Su) ->
                          T + Su 
                     end, 
                     0, 
                     Time),
   Sum / length(Time).
     

get_stddev(Time) ->
   Avg = get_avg(Time),
   Sum = lists:foldl(fun({_,T},Su) ->
                          math:pow((T - Avg),2) + Su 
                     end, 
                     0, 
                     Time),
   {math:sqrt(Sum / length(Time)),Sum}.
